/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Maps;
import dm.jdbc.util.StringUtil;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.Result;
import io.renren.controller.im.TencentCloudImUtil;
import io.renren.dao.ReservationmDao;
import io.renren.dto.*;
import io.renren.dto.queryDto.*;
import io.renren.entity.*;
import io.renren.factory.FeginClientFactory;
import io.renren.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Member接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api/Member")
@Api(tags = "Member - 接口")
@AllArgsConstructor
public class ApiMemberController {

    @Autowired
    private AutoService autoService;
    @Autowired
    private AutobrandService autobrandService;
    @Autowired
    private AutogroupService autogroupService;
    @Autowired
    private AutomodelsService automodelsService;
    @Autowired
    private RepairquotationmService repairquotationmService;
    @Autowired
    private ChatgroupService chatgroupService;
    @Autowired
    private UcmlOrganizeService ucmlOrganizeService;
    @Autowired
    private UcmlContactService ucmlContactService;
    @Autowired
    private RepairquotationitemsdService repairquotationitemsdService;
    @Autowired
    private RepairquotationpickingdService repairquotationpickingdService;
    @Autowired
    private AutorepairmService autorepairmService;
    @Autowired
    private ReservationmService reservationmService;
    @Autowired
    private ReservationmDao reservationmDao;
    @Autowired
    private AutorescueitemsdService autorescueitemsdService;
    @Autowired
    private TradermService tradermService;
    @Autowired
    private MakecardvouchersdService makecardvouchersdService;
    @Autowired
    private AgencyinsuranceregmService agencyinsuranceregmService;
    @Autowired
    private JoinmembermService joinmembermService;
    @Autowired
    private SaleoutstoremService saleoutstoremService;
    @Autowired
    private final WxuserService wxuserService;

    @PostMapping("bindCar")
    @ApiOperation("添加车辆")
    /**
     * 绑定车辆接口，用于新增或更新车辆信息。
     * 如果车辆已存在，则更新车辆信息；如果不存在，则创建新的车辆信息。
     *
     * @param traderMOID 经销商的唯一标识
     * @param dto 车辆信息的DTO对象，包含车辆的各种属性
     * @return 返回操作结果，成功或失败的信息
     */
    public Result<String> bindCar(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {
        // 检查车架号是否已存在
        if (StringUtil.isNotEmpty(dto.getAutoFrameNum())) {
            AutoEntity autoEntity = autoService.findOneByAutoFrameNum(dto.getAutoFrameNum());
            if (autoEntity != null) {
                return new Result().error("车辆已存在");
            }
        }
        // 检查车牌号是否已存在
        AutoEntity autoEntity = new AutoEntity();
        if (StringUtil.isNotEmpty(dto.getAutoNo())) {
            autoEntity = autoService.findOneByAutoNo(dto.getAutoNo());
            if (autoEntity != null && StringUtil.isNotEmpty(dto.getAutoNo())) {
                return new Result().error("车辆已被绑定");
            }
        }
        // 如果车辆不存在，则创建新的车辆信息
        if (autoEntity == null) {
            AutoEntity newInfo = new AutoEntity();
            // 设置品牌、集团、车型的外键ID，如果为空则设置为默认值
            if (StringUtil.isEmpty(dto.getAutoBrandFk())) {
                newInfo.setAutobrandFk("00000000-0000-0000-0000-000000000000");
            } else {
                newInfo.setAutobrandFk(dto.getAutoBrandFk());
            }
            if (StringUtil.isEmpty(dto.getAutoGroupFk())) {
                newInfo.setAutogroupFk("00000000-0000-0000-0000-000000000000");
            } else {
                newInfo.setAutogroupFk(dto.getAutoGroupFk());
            }
            if (StringUtil.isEmpty(dto.getAutoModelsFk())) {
                newInfo.setAutomodelsFk("00000000-0000-0000-0000-000000000000");
            } else {
                newInfo.setAutomodelsFk(dto.getAutoModelsFk());
            }

            // 查询品牌、集团、车型的详细信息
            AutobrandEntity autobrandEntity = autobrandService.findOneByAutoBrandOID(newInfo.getAutobrandFk());
            AutogroupEntity autogroupEntity = autogroupService.findOneByAutoGroupOID(newInfo.getAutogroupFk());
            AutomodelsEntity automodelsEntity = automodelsService.findOneByAutoModelsOID(newInfo.getAutomodelsFk());
            // 设置车辆唯一ID和创建、更新时间
            newInfo.setAutooid(UUID.randomUUID().toString());
            newInfo.setSysCreated(new Date());
            newInfo.setSysLastUpd(new Date());
            // 设置注册日期、车牌号、行驶里程等信息
            newInfo.setRegistrationdate(new Date());
            newInfo.setAutono(dto.getAutoNo());
            if (StringUtil.isNotEmpty(dto.getNowMileage())) {
                newInfo.setNowmileage(new BigDecimal(dto.getNowMileage()));
            }
            newInfo.setTradermFk(traderMOID);
            // 设置车架号和车型名称
            newInfo.setAutoframenum(dto.getAutoFrameNum());
            if (autobrandEntity != null && autogroupEntity != null && automodelsEntity != null) {
                newInfo.setAutomodelsname(autobrandEntity.getName() + " " + autogroupEntity.getName() + " " + automodelsEntity.getAutoyear() + "款" + automodelsEntity.getName() + automodelsEntity.getAutodisplacement());
            }

            // 设置年检日期和商业保险到期日
            if (StringUtil.isNotEmpty(dto.getYearlyCheckDate())) {
                newInfo.setYearlycheckdate(DateUtils.parse(dto.getYearlyCheckDate(), "yyyy-MM-dd"));
            }
            if (StringUtil.isNotEmpty(dto.getCommercialInsuranceEndDate())) {
                newInfo.setCommercialinsuranceenddate(DateUtils.parse(dto.getCommercialInsuranceEndDate(), "yyyy-MM-dd"));
            }

            // 如果是第一辆车，设置为默认车辆
            Long count = autoService.findOneByTraderMFkByTraderMOID(traderMOID);
            if (count == 0) {
                newInfo.setIsdefault(true);
            } else {
                newInfo.setIsdefault(false);
            }
            // 创建新的车辆信息
            autoService.createInfo(newInfo);
        } else {
            // 如果车辆已存在，更新车辆信息
            autoEntity.setTradermFk(traderMOID);
            autoService.updateInfo(autoEntity);
        }

        return new Result();
    }

    @PostMapping("quotationDetail")
    @ApiOperation("报价单详情")
    public Result<String> quotationDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody OrderDto dto) {
        if (StringUtil.isEmpty(dto.getRepairQuotationMoid())) {
            return new Result().error("报价记录ID不能为空");
        }
        Map<String, Object> map = new HashMap<>();
        RepairquotationmEntity repairquotationm = repairquotationmService.findOneByRepairQuotationMOID(dto.getRepairQuotationMoid());
        if (repairquotationm == null) {
            return new Result().error("报价单异常");
        }
        map.put("Org_FK", repairquotationm.getOrgFk());
        map.put("UCML_CONTACT_FK", repairquotationm.getUcmlContactFk());
        map.put("Auto_FK", repairquotationm.getAutoFk());
        map.put("TotalAmount", repairquotationm.getTotalamount());
        map.put("RepairQuotationMOID", repairquotationm.getRepairquotationmoid());
        map.put("IdentityDiscountAmount", repairquotationm.getIdentitydiscountamount());
        map.put("CardDeductionAmount", repairquotationm.getCarddeductionamount());
        map.put("Amount", repairquotationm.getAmount());
        map.put("IsCustomerConfirm", repairquotationm.getIscustomerconfirm());

        AutoEntity autoEntity = autoService.findOneByAutoOID(repairquotationm.getAutoFk());
        if (autoEntity == null) {
            map.put("AutoNo", autoEntity.getAutono());
        } else {
            map.put("AutoNo", "");
        }
        // 查询群聊ID
        ChatgroupEntity chatgroupEntity = chatgroupService.findOneByIMGroupID(autoEntity.getAutoframenum());
        if (chatgroupEntity != null) {
            map.put("groupId", chatgroupEntity.getImgroupid());
        } else {
            map.put("groupId", "");
        }

        UcmlOrganizeEntity organizeEntity = ucmlOrganizeService.findOneByOrganizeOID(repairquotationm.getOrgFk());
        if (organizeEntity != null) {
            map.put("orgName", organizeEntity.getOrgname());
        } else {
            map.put("orgName", "");
        }
        UcmlContactEntity contactEntity = ucmlContactService.findOneByCONTACTOID(repairquotationm.getUcmlContactFk());
        if (contactEntity != null) {
            map.put("PersonName", contactEntity.getPersonname());
        } else {
            map.put("PersonName", "");
        }

        DecimalFormat df = new DecimalFormat("#.00");
        // 服务项目
        List<RepairquotationitemsdEntity> quotationitemsds = repairquotationitemsdService.getListByRepairQuotationMFK(repairquotationm.getRepairquotationmoid());
        List<Map<String, Object>> projectList = new ArrayList<>();
        for (RepairquotationitemsdEntity item : quotationitemsds) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("projectName", item.getServicename());
            map1.put("Amount", df.format(Double.valueOf(item.getAmount())));
            map1.put("price", df.format(item.getPrice()));
            map1.put("BusinessAmount", df.format(Double.valueOf(item.getBusinessamount())));
            projectList.add(map1);
        }
        map.put("projectList", projectList);

        // 材料

        List<RepairquotationpickingdEntity> pickingds = repairquotationpickingdService.getListByRepairQuotationMFk(repairquotationm.getRepairquotationmoid());
        List<Map<String, Object>> goodList = new ArrayList<>();
        for (RepairquotationpickingdEntity item : pickingds) {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("BusinessQuantity", item.getBusinessquantity().setScale(2, RoundingMode.HALF_UP));
            map2.put("Amount", new BigDecimal(item.getAmount()).setScale(2, RoundingMode.HALF_UP));
            map2.put("price", item.getPrice().setScale(2, RoundingMode.HALF_UP));
            map2.put("BusinessAmount", df.format(Double.valueOf(item.getBusinessamount())));
            map2.put("unitName", item.getBusinessunit());
            map2.put("GoodsName", item.getGoodsname());
            goodList.add(map2);
        }
        map.put("goodsList", goodList);

        map.put("BillDate", DateUtils.format(repairquotationm.getBilldate(), "yyyy-MM-dd"));
        if (StringUtils.isNotEmpty(repairquotationm.getTotalamount())) {
            map.put("TotalAmount", String.format("%.2f", Double.valueOf(repairquotationm.getTotalamount())));
        } else {
            map.put("TotalAmount", "");
        }
        if (StringUtils.isNotEmpty(repairquotationm.getIdentitydiscountamount())) {
            map.put("IdentityDiscountAmount", String.format("%.2f", Double.valueOf(repairquotationm.getIdentitydiscountamount())));
        } else {
            map.put("IdentityDiscountAmount", "");
        }
        if (StringUtils.isNotEmpty(repairquotationm.getCarddeductionamount())) {
            map.put("CardDeductionAmount", String.format("%.2f", Double.valueOf(repairquotationm.getCarddeductionamount())));
        } else {
            map.put("CardDeductionAmount", "");
        }

        map.put("Amount", df.format(Double.valueOf(repairquotationm.getAmount())));

        return new Result().ok(map);
    }


    @PostMapping("myAutoList")
    @ApiOperation("我的车辆列表")
    public Result<List<Map<String, Object>>> myAutoList(@RequestHeader("TraderMOID") String traderMOID) {
        List<Map<String, Object>> list = autoService.getMapByTraderMFk(traderMOID);
        return new Result().ok(list);
    }

    @PostMapping("setAutoDefault")
    @ApiOperation("设置默认车辆")
    public Result setAutoDefault(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {
        autoService.setAutoDefault(traderMOID, dto.getAutoOID());
        return new Result();
    }

    @PostMapping("myAutoInfo")
    @ApiOperation("我的车辆信息详情")
    public Result<Map<String, Object>> myAutoInfo(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {
        Map<String, Object> map = autoService.myAutoInfo(traderMOID, dto.getAutoOID());
        return new Result().ok(map);
    }

    @PostMapping("myAutoEdit")
    @ApiOperation("我的车辆信息修改")
    @Transactional(rollbackFor = Exception.class)
    public Result myAutoEdit(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {

        AutobrandEntity autobrandEntity = autobrandService.findOneByAutoBrandOID(dto.getAutoBrandFk());
        AutogroupEntity autogroupEntity = autogroupService.findOneByAutoGroupOID(dto.getAutoGroupFk());
        AutomodelsEntity automodelsEntity = automodelsService.findOneByAutoModelsOID(dto.getAutoModelsFk());

        AutoEntity autoEntity = new AutoEntity();
        autoEntity.setAutooid(dto.getAutoOID());
        if (autobrandEntity == null) {
            return new Result().error("车辆信息不存在");
        }
        autoEntity.setSysLastUpdBy("00000000-0000-0000-0000-000000000001");
        autoEntity.setSysLastUpd(new Date());
        if (dto.getNowMileage() != null && StringUtil.isNotEmpty(dto.getNowMileage())) {
            autoEntity.setNowmileage(new BigDecimal(dto.getNowMileage()));
        }
        if (autobrandEntity != null && autogroupEntity != null && automodelsEntity != null) {
            autoEntity.setAutomodelsname(autobrandEntity.getName() + " " + autogroupEntity.getName() + " " + automodelsEntity.getAutoyear() + "款" + automodelsEntity.getName() + automodelsEntity.getAutodisplacement());
        }
        autoEntity.setAutobrandFk(dto.getAutoBrandFk());
        autoEntity.setAutogroupFk(dto.getAutoGroupFk());
        autoEntity.setAutomodelsFk(dto.getAutoModelsFk());
        if (StringUtil.isNotEmpty(dto.getYearlyCheckDate())) {
            autoEntity.setYearlycheckdate(DateUtils.parse(dto.getYearlyCheckDate(), "yyyy-MM-dd"));
        }
        if (StringUtil.isNotEmpty(dto.getTrafficInsuranceEndDate())) {
            autoEntity.setCompulsoryinsuranceenddate(DateUtils.parse(dto.getTrafficInsuranceEndDate(), "yyyy-MM-dd"));
        }
        if (StringUtil.isNotEmpty(dto.getCommercialInsuranceEndDate())) {
            autoEntity.setCommercialinsuranceenddate(DateUtils.parse(dto.getCommercialInsuranceEndDate(), "yyyy-MM-dd"));
        }
        // autoEntity.setEnginenum(dto.getEngineNum);
        if (StringUtil.isNotEmpty(dto.getAutoFrameNum())) {
            autoEntity.setAutoframenum(dto.getAutoFrameNum());
        }
        autoService.updateInfo(autoEntity);

        autoEntity = autoService.findOneByAutoOID(dto.getAutoOID());
        Long count = autoService.findOneByTraderMFkByAutoFrameNum(autoEntity.getAutoframenum());
        if (count > 0 && !dto.getAutoOID().equals(autoEntity.getAutooid())) {
            return new Result().error("车辆已存在");
        }
        return new Result();
    }

    @PostMapping("myAutoDel")
    @ApiOperation("我的车辆信息删除")
    @Transactional(rollbackFor = Exception.class)
    public Result myAutoDel(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {
        if (StringUtil.isEmpty(dto.getAutoOID())) {
            return new Result().error("参数错误");
        }
        autoService.deleteByAutoOIDAndTraderMDK(traderMOID, dto.getAutoOID());
        return new Result();
    }

    @PostMapping("myAutoServiceList")
    @ApiOperation("我的车辆服务记录")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> myAutoServiceList(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {
        if (StringUtil.isEmpty(dto.getAutoOID())) {
            return new Result().error("参数错误");
        }
        Map<String, Object> map = autorepairmService.myAutoServiceList(traderMOID, dto.getAutoOID(), dto.getPage(), dto.getPageSize());
        return new Result().ok(map);
    }

    @PostMapping("quotationConfirm")
    @ApiOperation("报价单确认报价")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> quotationConfirm(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CarDto dto) {
        if (StringUtil.isEmpty(dto.getRepairQuotationMOID())) {
            return new Result().error("报价记录ID不能为空");
        }
        repairquotationmService.quotationConfirm(traderMOID, dto.getRepairQuotationMOID());
        return new Result();
    }

    @PostMapping("myReservationList")
    @ApiOperation("我的预约列表")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> myReservationList(@RequestHeader("TraderMOID") String traderMOID) {
        Map<String, Object> res = reservationmService.myReservationList(traderMOID);
        return new Result().ok(res);
    }

    @PostMapping("reservation")
    @ApiOperation("发起预约")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> reservation(@RequestHeader("TraderMOID") String traderMOID, @RequestBody ReservationDto dto) {
        reservationmService.reservation(traderMOID, dto);
        return new Result();
    }


    @PostMapping("cancelReservation")
    @ApiOperation("取消预约")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> cancelReservation(@RequestHeader("TraderMOID") String traderMOID, @RequestBody ReservationDelDto dto) {
        reservationmService.cancelReservation(traderMOID, dto.getReservationMoId(), dto.getCancelReason());
        return new Result();
    }

    @PostMapping("serviceList")
    @ApiOperation("服务单列表")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> serviceList(@RequestHeader("TraderMOID") String traderMOID, @RequestBody ServerListQueryDto dto) {
        Map<String, Object> map = autorescueitemsdService.serviceList(traderMOID, dto);
        return new Result().ok(map);
    }

    @PostMapping("memberInfo")
    @ApiOperation("我的信息")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> memberInfo(@RequestHeader("TraderMOID") String traderMOID) {
        Map<String, Object> map = tradermService.memberInfo(traderMOID);
        return new Result().ok(map);
    }


    @PostMapping("updateUserInfo")
    @ApiOperation("更新名称和头像")
    @Transactional(rollbackFor = Exception.class)
    public Result updateUserInfo(@RequestHeader("TraderMOID") String traderMOID, @RequestBody UserInfoDto dto) {
        TradermEntity userInfo = tradermService.updateUserInfo(traderMOID, dto);
        // 更新 IM 的头像
        tencentCloudImUtil.setPortraitManage(userInfo.getTel(), dto.getHeadImg());
        // 更新 WxUser 表
        WxuserEntity wxuserEntity = new WxuserEntity();
        if (StringUtil.isNotEmpty(dto.getUserName()) && StringUtil.isNotEmpty(userInfo.getMiniopenid())) {
            wxuserEntity.setWxnickname(dto.getUserName());
            wxuserService.update(wxuserEntity, new QueryWrapper<WxuserEntity>().eq("MiniOpenID", userInfo.getMiniopenid()));
        }
        if (StringUtil.isNotEmpty(dto.getHeadImg()) && StringUtil.isNotEmpty(userInfo.getMiniopenid())) {
            wxuserEntity.setWxheadimageurl(dto.getHeadImg());
            wxuserService.update(wxuserEntity, new QueryWrapper<WxuserEntity>().eq("MiniOpenID", userInfo.getMiniopenid()));
        }
        return new Result();
    }


    @PostMapping("couponsList")
    @ApiOperation("我的卡券列表")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> couponsList(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CouponsDto dto) {
        return new Result().ok(makecardvouchersdService.couponsList(traderMOID, dto));
    }

    @PostMapping("sendCoupons")
    @ApiOperation("卡券赠送")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> sendCoupons(@RequestHeader("TraderMOID") String traderMOID, @RequestBody SendCouponsDto dto) {
        Map<String, Object> map = makecardvouchersdService.sendCoupons(traderMOID, dto);
        return new Result().ok(map);
    }

    @PostMapping("acceptCoupons")
    @ApiOperation("卡券接受")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> acceptCoupons(@RequestHeader("TraderMOID") String traderMOID, @RequestBody AcceptCouponsDto dto) {
        Map<String, Object> map = makecardvouchersdService.acceptCoupons(traderMOID, dto);
        return new Result().ok(map);
    }


    @PostMapping("serviceProgress")
    @ApiOperation("卡券接受")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> serviceProgress(@RequestHeader("TraderMOID") String traderMOID, @RequestBody BusinessKeyDto dto) {
        Map<String, Object> map = autorepairmService.serviceProgress(traderMOID, dto);
        return new Result().ok(map);
    }

    @PostMapping("insureDetail")
    @ApiOperation("保险详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> insureDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody InsureDetailDto dto) {
        Map<String, Object> map = agencyinsuranceregmService.insureDetail(traderMOID, dto);
        return new Result().ok(map);
    }

    @PostMapping("vipDetail")
    @ApiOperation("车辆VIP详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> vipDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody VipDetailDto dto) {
        Map<String, Object> map = joinmembermService.vipDetail(traderMOID, dto);
        return new Result().ok(map);
    }

    @PostMapping("saleDetail")
    @ApiOperation("销售服务单详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> saleDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody SaleDetailDto dto) {
        Map<String, Object> map = saleoutstoremService.saleDetail(traderMOID, dto);
        return new Result().ok(map);
    }

    @Autowired
    private AutowashmService autowashmService;

    @PostMapping("washDetail")
    @ApiOperation("洗车详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> washDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody WashDetailDto dto) {
        Map<String, Object> map = autowashmService.washDetail(traderMOID, dto);
        return new Result().ok(map);
    }

    @Autowired
    private AutoservicemService autoservicemService;

    @PostMapping("serviceDetail")
    @ApiOperation("车务详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> serviceDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody ServiceDetailDto dto) {
        Map<String, Object> map = autoservicemService.serviceDetail(traderMOID, dto);
        return new Result().ok(map);
    }

    @Autowired
    private AutorescuemService autorescuemService;

    @PostMapping("saveDetail")
    @ApiOperation("救援详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> saveDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody SaveDetailDto dto) {
        Map<String, Object> map = autorescuemService.saveDetail(traderMOID, dto);
        return new Result().ok(map);
    }

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @PostMapping("getUserSign")
    @ApiOperation("获取im userSign")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> getUserSign(@RequestHeader("TraderMOID") String traderMOID, @RequestBody UserSignDto dto) {
        String userSig = tencentCloudImUtil.getTxCloudUserSig(dto.getUserId());
        return new Result().ok(userSig);
    }


    @Autowired
    private MakecardvouchersmService makecardvouchersService;

    @PostMapping("waitReceivedCoupons")
    @ApiOperation("我的待接收卡券")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> waitReceivedCoupons(@RequestHeader("TraderMOID") String traderMOID) {
        return new Result().ok(makecardvouchersService.waitReceivedCoupons(traderMOID));
    }


    @Autowired
    private AutodecoratemService autodecoratemService;

    @PostMapping("autoDecorateDetail")
    @ApiOperation("美容详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> autoDecorateDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody DecorateDetailDto dto) {
        return new Result().ok(autodecoratemService.autoDecorateDetail(traderMOID, dto));
    }


    @PostMapping("autoRepairDetail")
    @ApiOperation("维修详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> autoRepairDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody RepairDetailDto dto) {
        return new Result().ok(autorepairmService.autoRepairDetail(traderMOID, dto));
    }

    @PostMapping("autoReturnRepairDetail")
    @ApiOperation("返修详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> autoReturnRepairDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody ReturnRepairDetailDto dto) {
        return new Result().ok(autorepairmService.autoReturnRepairDetail(traderMOID, dto));
    }

    @PostMapping("autoBaoYangDetail")
    @ApiOperation("保养详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> autoBaoYangDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody BaoYangDetailDto dto) {
        return new Result().ok(autorepairmService.autoBaoYangDetail(traderMOID, dto));
    }

    @PostMapping("settlementList")
    @ApiOperation("结算清单")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> settlementList(@RequestHeader("TraderMOID") String traderMOID, @RequestBody TlementDto dto) {
        SettlementMInfoQuery query = new SettlementMInfoQuery();
        query.setBillOID(dto.getBillOID());
        query.setContactFk(dto.getContactFk());
        query.setBillType(dto.getBillType());
        query.setIsOnlyCheck(true);
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").settlementMInfo(query);
        return new Result().ok(result);
    }

    @PostMapping("SettlementMNewGenerate")
    @ApiOperation("业务单据生成结算单接口")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> SettlementMNewGenerate(@RequestHeader("TraderMOID") String traderMOID, @RequestBody TlementDto dto) {
        SettlementMInfoQuery query = new SettlementMInfoQuery();
        query.setBillOID(dto.getBillOID());
        query.setContactFk(dto.getContactFk());
        query.setBillType(dto.getBillType());
        query.setIsOnlyCheck(true);
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").settlementMNewGenerate(query);
        return new Result().ok(result);
    }

    @PostMapping("SettlementMInfo")
    @ApiOperation("结算单详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> SettlementMInfo(@RequestHeader("TraderMOID") String traderMOID, @RequestBody TlementDto dto) {
        SettlementMInfoQuery query = new SettlementMInfoQuery();
        query.setBillOID(dto.getBillOID());
        query.setContactFk(dto.getContactFk());
        query.setBillType(dto.getBillType());
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").settlementMInfo(query);
        return new Result().ok(result);
    }


    @PostMapping("UseSetCardsList")
    @ApiOperation("获取抵扣后卡券列表")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> UseSetCardsList(@RequestHeader("TraderMOID") String traderMOID, @RequestBody UseSetCardsDto dto) {
        UseSetCardsQuery query = new UseSetCardsQuery();
        query.setSettlementMoId(dto.getSettlementMoId());
        query.setContactFk(dto.getContactFk());
        query.setIsCanUse(true);
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getUseSetCardsList(query);
        return new Result().ok(result);
    }

    @PostMapping("SetCardDeduction")
    @ApiOperation("卡券抵扣")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> SetCardDeduction(@RequestHeader("TraderMOID") String traderMOID, @RequestBody UseSetCardsDto dto) {
        CardDeductionQuery query = new CardDeductionQuery();
        query.setSettlementMoId(dto.getSettlementMoId());
        query.setContactFk(dto.getContactFk());
        query.setSourceCardProjectGoodsDetailOID(dto.getSourceCardProjectGoodsDetailOId());
        query.setIsCalculate(true);
        query.setUseQuantityAmount(dto.getUseQuantityAmount());
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").setCardDeduction(query);
        return new Result().ok(result);
    }

    @PostMapping("GetSettlementPayQRCode")
    @ApiOperation("获取结算单支付二维码地址")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> GetSettlementPayQRCode(@RequestHeader("TraderMOID") String traderMOID, @RequestBody PayQRCodeDto dto) {
        ParByKeyQuery query = new ParByKeyQuery();
        query.setKey("SettlementPayWay");
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getQuerySysParByKey(query);

        PayQRCodeQuery qrCodeQuery = new PayQRCodeQuery();
        qrCodeQuery.setPayKinds(result.getData().toString());
        qrCodeQuery.setBillOId(dto.getBillOID());
        qrCodeQuery.setContactFk(dto.getContactFk());
        qrCodeQuery.setNotifyUrl(dto.getReturnUrl());
        qrCodeQuery.setReturnUrll(dto.getReturnUrl());
        ReturnApiDto result2 = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getSettlementPayQRCode(qrCodeQuery);
        return new Result().ok(result2);
    }

    @PostMapping("GetSettlementPayState")
    @ApiOperation("查询结算单支付状态")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> GetSettlementPayState(@RequestHeader("TraderMOID") String traderMOID, @RequestBody PayStateDto dto) {
        PayStateQuery query = new PayStateQuery();
        query.setBillOID(dto.getBillOID());
        query.setContactFk(dto.getContactFk());
        query.setBillType(dto.getBillType());
        query.setOutTradeNo(dto.getOutTradeNo());
        query.setIsOnlyCheck(true);
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getSettlementPayState(query);
        return new Result().ok(result);
    }

    @PostMapping("IMGroupIDInfo")
    @ApiOperation("查询结算单支付状态")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> IMGroupIDInfo(@RequestHeader("TraderMOID") String traderMOID, @RequestBody IMGroupDto dto) {
        IMGroupQuery query = new IMGroupQuery();
        query.setBillOID(dto.getBillOID());
        query.setContactFk(dto.getContactFk());
        query.setBillType(dto.getBillType());
        query.setIsOnlyCheck(true);
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getIMGroupIDInfo(query);
        return new Result().ok(result);
    }

    @PostMapping("CancelSetCardDeduction")
    @ApiOperation("取消卡券抵扣")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> CancelSetCardDeduction(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CancelSetCardDeductionDto dto) {
        CancelSetCardDeductionQuery query = new CancelSetCardDeductionQuery();
        query.setSettlementMOID(dto.getSettlementMOID());
        query.setContactFk(dto.getContactFk());
        query.setSourceCardProjectGoodsDetailOID(dto.getSourceCardProjectGoodsDetailOID());
        query.setIsCalculate(true);
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").cancelSetCardDeduction(query);
        return new Result().ok(result);
    }

    @PostMapping("couponDetail")
    @ApiOperation("卡券详情")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> couponDetail(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CancelSetCardDeductionDto dto) {
        CardsInfoQuery query = new CardsInfoQuery();
        query.setMakeCardVouchersDOID(dto.getMakeCardVouchersDOID());
        ReturnApiDto result = FeginClientFactory.getFeginClient(FeginClientProxy.class, "http://58.216.180.2:8405/").getCardsInfo(query);
        return new Result().ok(result);
    }

    @PostMapping("refuseCoupon")
    @ApiOperation("拒绝接收卡券")
    @Transactional(rollbackFor = Exception.class)
    public Result<Map<String, Object>> refuseCoupon(@RequestHeader("TraderMOID") String traderMOID, @RequestBody CancelSetCardDeductionDto dto) {
        if (StringUtil.isEmpty(dto.getMakeCardVouchersDOID())) {
            return new Result().error("参数错误");
        }
        makecardvouchersdService.refuseCoupon(dto.getMakeCardVouchersDOID());
        return new Result();
    }

    @PostMapping("logout")
    @ApiOperation("退出")
    public Result logout(@RequestHeader("TraderMOID") String traderMOID) {
        WxuserEntity wxuserEntity = wxuserService.findOneByTraderMOID(traderMOID);
        if (wxuserEntity != null) {
            wxuserService.setTraderMFKIsNull(wxuserEntity.getWxuseroid());
        }
        return new Result();
    }


    @GetMapping("getImSdkId")
    @ApiOperation("我的车辆信息详情")
    public Result<Map<String, Object>> getImSdkId() {
        Map<String, Object> map = Maps.newHashMap();
        map.put("sdkAppId", "1600045409");
        return new Result().ok(map);
    }

}